package com.ljfiction.book.activitys;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.SmoothCheckBox;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.Md5;
import com.ljfiction.book.http.UserBean;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.PreferencesTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.mob.tools.utils.UIHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;


public class LoginActivity extends BaseActivity implements Handler.Callback, PlatformActionListener {

    @BindView(R.id.login_daphanglan)
    LinearLayout loginDaphanglan;
    @BindView(R.id.back_login)
    ImageView backLogin;
    @BindView(R.id.poneword_login)
    EditText ponewordLogin;
    @BindView(R.id.password_login)
    EditText passwordLogin;
    @BindView(R.id.remembercheck)
    SmoothCheckBox remembercheck;
    @BindView(R.id.loginin)
    SuperButton loginin;
    @BindView(R.id.registration_login)
    TextView registrationLogin;
    @BindView(R.id.retrieve_login)
    TextView retrieveLogin;
    @BindView(R.id.logbackgrand)
    LinearLayout logbackgrand;

    @BindView(R.id.lookpassword)
    ImageView lookpassword;
    @BindView(R.id.qqlogin)
    ImageView qqlogin;

    private boolean isChecket = false;
    private Intent intent;
    private NoBackgLodDialog loadingDialog;


    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;


    String type_l = "";//	是	string	微信：wx qq:qq 新浪：sina

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //SoftHideKeyBoardUtil.assistActivity(this);

        intView();
    }


    private void intView() {
        todaohanglanHeight(loginDaphanglan, this);
        remembercheck.setChecked(true);
        if ("1".equals(PreferencesTool.getValue(this, "isChecked"))) {
            ponewordLogin.setText(PreferencesTool.getUserName(this));
            passwordLogin.setText(PreferencesTool.getPassWord(this));
        }
        ponewordLogin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if ("1".equals(PreferencesTool.getValue(LoginActivity.this, "isChecked")) && !String.valueOf(charSequence).equals(PreferencesTool.getUserName(LoginActivity.this))) {
                    passwordLogin.setText("");
                } else if ("1".equals(PreferencesTool.getValue(LoginActivity.this, "isChecked")) && String.valueOf(charSequence).equals(PreferencesTool.getUserName(LoginActivity.this))) {
                    passwordLogin.setText(PreferencesTool.getPassWord(LoginActivity.this));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @OnClick({R.id.back_login, R.id.remembercheck, R.id.loginin, R.id.registration_login, R.id.retrieve_login, R.id.lookpassword, R.id.qqlogin, R.id.weixinlogin, R.id.weibologin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_login:
                goBack();
                break;
            case R.id.remembercheck:
                if (remembercheck.isChecked()) {
                    remembercheck.setChecked(false, true);
                } else {
                    remembercheck.setChecked(true, true);
                }
                break;
            case R.id.loginin:

                if ("".equals(ponewordLogin.getText().toString())) {
                    showToast("请输入手机号");
                } else if ("".equals(passwordLogin.getText().toString())) {
                    showToast("请输入密码");
                } else if (!StringTool.isPass(passwordLogin.getText().toString())) {
                    showToast(StringTool.isPassString(passwordLogin.getText().toString()));
                    return;
                } else {

                    dologin();
                }
                EventTool.putEvent(LoginActivity.this, "点击", "点击", "9_loginClick");
                break;
            case R.id.registration_login:
                EventTool.putEvent(LoginActivity.this, "点击", "点击", "10_registeredClick");
                intent = new Intent(this, RetrieveActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.retrieve_login:
                intent = new Intent(this, FindPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.lookpassword:
                if (isChecket) {
                    isChecket = false;
                    passwordLogin.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    lookpassword.setImageResource(R.mipmap.eyebi);
                } else {
                    isChecket = true;
                    passwordLogin.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    lookpassword.setImageResource(R.mipmap.eyekai);
                }
                break;
            case R.id.qqlogin:
                authorize(ShareSDK.getPlatform(QQ.NAME));
                type_l = "qq";
                break;
            case R.id.weixinlogin:
                authorize(ShareSDK.getPlatform(Wechat.NAME));
                type_l = "wx";
                break;
            case R.id.weibologin:
                authorize(ShareSDK.getPlatform(SinaWeibo.NAME));
                type_l = "xl";
                break;
        }
    }










    private void authorize(Platform plat) {
        if (plat == null) {
            return;
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    private void dologin() {

        OkHttpUtils.post(HttpManager.IP + "/person-login")
                .params("userName", ponewordLogin.getText().toString())
                .params("userPassword",Md5.encryption(passwordLogin.getText().toString()) )
                .params("terminal", "2")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(LoginActivity.this, true);
                        }
                        loadingDialog.show();
                        request.getHeaders().remove("cookie");
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }

                        try {
                            // 取得sessionid.
                           /* Headers headers = response.headers();
                            List<String> cookies = headers.values("Set-Cookie");
                            String session = cookies.get(0);
                            session = session.substring(0, session.indexOf(";"));
                            SettingManager.getInstance().savesessionId(session);
                            HttpHeaders httpHeaders=new HttpHeaders();
                            httpHeaders.put("cookie",SettingManager.getInstance().getSessionId());
                            OkHttpUtils.getInstance().addCommonHeaders(httpHeaders);*/
                            Gson gson = new Gson();
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                enjoin(user);
                                if (user.getsTR() == 1) {
                                    Tool.xmjaddtishi(LoginActivity.this);
                                    UserManageBean.userBean.setsTR(0);
                                } else {
                                    showToast("登陆成功");
                                }
                            } else {
                                showToast(jsonObject.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    private void enjoin(UserBean user) {
        PreferencesTool.saveLoginInfo(this, ponewordLogin.getText().toString(), passwordLogin.getText().toString());
        PreferencesTool.saveValue(this, "userId", user.getUserId() + "");
        PreferencesTool.saveValue(this, "isCache", "1");
        SettingManager.getInstance().savesessionId(user.getToken());
        if (remembercheck.isChecked()) {
            PreferencesTool.saveValue(this, "isChecked", "1");
        } else {
            PreferencesTool.saveValue(this, "isChecked", "0");
        }
        UserManageBean.userBean = user;
        UserManageBean.setIsLogin(true);
        goBack();


    }

    /**
     * 获取到用户信息进行第三方登录
     */
    private void loginStacks(HashMap<String, Object> res) {
        Gson gson = new Gson();
        switch (type_l) {
            case "qq":
                enjoinDisanfang("/person-LaJiXiaoShuoAppQQLogin", "QQServerJson", gson.toJson(res), (String) res.get("token"));
                break;
            case "wx":
                enjoinDisanfang("/person-LaJiXiaoShuoAppWeChatLogin", "weChatServerJson", gson.toJson(res), (String) res.get("unionid"));

                break;
            case "xl":
                enjoinDisanfang("/person-LaJiXiaoShuoAppSinaLogin", "sinaServerJson", gson.toJson(res), (String) res.get("openId"));

                break;
        }


    }

    private void enjoinDisanfang(String url, String key, String json, String passWordDisanfang) {
        Log.v("wx", "wx" + url + "wx" + key + "wx" + json);
        OkHttpUtils.post(HttpManager.IP + url)
                .params(key, json)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(LoginActivity.this, true);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }
                        // 取得sessionid.
                       /* Headers headers = response.headers();
                        List<String> cookies = headers.values("Set-Cookie");
                        String session = cookies.get(0);
                        session = session.substring(0, session.indexOf(";"));
                        SettingManager.getInstance().savesessionId(session);*/
                        Gson gson = new Gson();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                try {
                                    PreferencesTool.saveLoginInfo(LoginActivity.this, user.getUserName(), passWordDisanfang);
                                    PreferencesTool.saveValue(LoginActivity.this, "userId", user.getUserId() + "");
                                    PreferencesTool.saveValue(LoginActivity.this, "isCache", "1");
                                    PreferencesTool.saveValue(LoginActivity.this, "isChecked", "0");
                                    PreferencesTool.saveValue(LoginActivity.this, "issanfang", "1");
                                    UserManageBean.userBean = user;
                                    SettingManager.getInstance().savesessionId(user.getToken());
                                    UserManageBean.setIsLogin(true);
                                    goBack();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    goBack();
                                }
                                if (type_l.equals("qq")) {
                                    try {
                                        togetPassword(user.getUserName(),passWordDisanfang);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }


                                if (user.getsTR() == 1) {
                                    Tool.xmjaddtishi(LoginActivity.this);
                                    UserManageBean.userBean.setsTR(0);
                                } else {
                                    showToast("登陆成功");
                                }
                            } else {
                                showToast(jsonObject.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                });

    }

    /*
     * qq登陆需要请求得到unionid当作密
     * */
    private void togetPassword(String username,String passWordDisanfang) {
        OkHttpUtils.get("https://graph.qq.com/oauth2.0/me?access_token=" + passWordDisanfang + "&unionid=1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            PreferencesTool.saveLoginInfo(LoginActivity.this, username, s.substring(s.indexOf("UID_"), s.lastIndexOf("\"}")));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 10) {
            goBack();
        }
    }

    @Override
    public boolean handleMessage(Message message) {

        switch (message.what) {
            case MSG_USERID_FOUND: {
                showToast("userid_found");
            }
            break;
            case MSG_LOGIN: {
                loginStacks((HashMap<String, Object>) message.obj);
            }
            break;
            case MSG_AUTH_CANCEL: {
                //showToast("auth_cancel");
                System.out.println("-------MSG_AUTH_CANCEL--------");
            }
            break;
            case MSG_AUTH_ERROR: {
                //showToast("auth_cancel");
                System.out.println("-------MSG_AUTH_ERROR--------");
            }
            break;
            case MSG_AUTH_COMPLETE: {
                System.out.println("--------MSG_AUTH_COMPLETE-------");
            }
            break;
        }
        return false;
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        Log.v("回调成功", action + "" + hashMap.toString());
        if (action == Platform.ACTION_USER_INFOR) {
            //UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
            hashMap.put("userCode", StringTool.getChannelName(LoginActivity.this));
            hashMap.put("terminal", "2");
            hashMap.put("token", platform.getDb().getToken());
            hashMap.put("openId", platform.getDb().getUserId());
            hashMap.put("userImage", platform.getDb().getUserIcon());
            login(hashMap);
            if (platform.isAuthValid()) {
                platform.removeAccount(true);
            }
            //isValid和removeAccount不开启线程，会直接返回。
        }
    }

    private void login(HashMap<String, Object> userInfo) {
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = userInfo;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        Log.v("回调失败", action + "" + platform.toString());
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Log.v("回调关闭", action + "");
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }
}
